package de.tum.in.eist.poll.client;

import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

/***
 * view for the lecturer to manage Student IDs
 */
public class ManageIDsView {
	static void paint() {
		if(Poll.lecturer == null){
			History.newItem("lecturerLogin");	return;
		}
		RootPanel.get("logo").addStyleName("logo-small");
		final FlexTable idTable = new FlexTable();
		idTable.setWidget(0, 0, new HTML("<u>Student ID</u>"));
		idTable.addStyleName("idTable");
		Poll.adminService.getUserMatrikelList(Poll.lecturer , new AsyncCallback<List<String>>(){
			@Override
			public void onFailure(Throwable caught) {
			}
			@Override
			public void onSuccess(List<String> result) {
				if(result == null){
					History.newItem("lecturerLogin");
					return;
				}
				for(String s : result){
					idTable.setText(idTable.getRowCount(), 0, s);
					// TODO: Delete Button
				}
				final TextBox addBox = new TextBox();
				idTable.setWidget(idTable.getRowCount(),0,addBox);
				final Button addButton = new Button("Add Student ID");
				idTable.setWidget(idTable.getRowCount()-1,1,addButton);
				class AddHandler implements ClickHandler, KeyUpHandler {
					public void onClick(ClickEvent event) {
						addToServer();
					}
					public void onKeyUp(KeyUpEvent event) {
						if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
							addToServer();
						}
					}
					public void addToServer() {
						final String studentID = addBox.getText();
						addBox.setText("");
						addBox.setFocus(false);
						addBox.getElement().setAttribute("placeholder", "Adding...");
						
						Poll.adminService.addUser(Poll.lecturer, studentID, new AsyncCallback<Void>() {
							public void onFailure(Throwable caught) {
								addBox.setText("");
								addBox.setFocus(false);
								addBox.getElement().setAttribute("placeholder", "Network-Error");
							}
							public void onSuccess(Void result) {
								idTable.setText(idTable.insertRow(idTable.getRowCount()-1),0,studentID);
								addBox.setText("");
								addBox.setFocus(false);
								addBox.getElement().setAttribute("placeholder", "Added");
							}
						});
					}
				}
				AddHandler ah = new AddHandler();
				addBox.addKeyUpHandler(ah);
				addButton.addClickHandler(ah);
			}
		});
		RootPanel.get("container").add(idTable);
	}
}
